/* Author: Bin Fan */

$(document).ready(function() {
    get_all_data();
//    makeChart();
    google.load('visualization', '1', {'packages':['annotatedtimeline'], 'callback':add_count});
});

function toDate(t) {
	t *= 1000; // to milliseconds
	return new Date(t)
}


var history = {};
var data_length = 1343052;
var finish_loading = 0;

function get_all_data() {
	get_weather_data('tempc');
	get_weather_data('humidity');
	get_weather_data('pressure');
}

function add_count() {
    finish_loading += 1;
   	if (finish_loading == 4) {
   		make_chart();
   	}
}

function get_weather_data(metricname) {
	
	//uncompressed data
	/*$.get(
  		'data/?uncompress&metric='+metricname,
	    function (data) {
	        var buffer = new jDataView(data);
	       	rdata = [];
	       	for (var i = 0; i < data_length; ++i) {
	       		rdata.push(buffer.getFloat32());
	       	}
	       	console.log(metricname, rdata.length);
	       	history[metricname] = rdata;
	       	add_count();
	    },
	    'binary'
    );*/
    
	$.get(
  		'data/?metric='+metricname,
	    function (data) {
	        var buffer = new jDataView(data);
	        var decoder = new jPipeDecoder();
	        history[metricname] = decoder.decode(buffer);
          console.log('history', history[metricname]);
          add_count();
	    },
	    'binary'
    );
    
}

function make_chart() {
	var alldata = new google.visualization.DataTable();
   	
   	console.log(finish_loading);

    alldata.addColumn('datetime', 'Date');
    alldata.addColumn('number', 'TempC');
    alldata.addColumn('number', 'Humidity %');
    alldata.addColumn('number', 'Pressure (KPa)');
	
    var curTime = 1326127921;
	  var curTemp = history['tempc'][0];

    var real_length = data_length;
    real_length = Math.min(data_length, history['tempc'].length,
          history['humidity'].length, history['pressure'].length);
    var step = Math.max(Math.ceil(real_length / 10000), 1);
    console.log('real:', step, real_length);
    for (i = 0; i < real_length; i += step) {
		curTime += step;
		curTemp = (history['tempc'][i] + curTemp) / 2;
		var curHumidity = history['humidity'][i];
		var curPressure = history['pressure'][i];
		alldata.addRow([new Date(curTime*1000), curTemp, curHumidity, curPressure/1000]);
    }

    var options = {
        width: 400, height: 240,
        title: 'Temperature History',
	    scaleType: 'allmaximized',
        displayAnnotations: false
    };

    var chart = new google.visualization.AnnotatedTimeLine(
        document.getElementById('chart_div'));
    chart.draw(alldata, options);
}

